const { executeQuery, baseQuery } = require('./mongo_util')
const collectionName = "dormitory";

function add(carts, onRetGot, onErrGot) {
    executeQuery(collectionName, (collection, callback) => {
        collection.insertOne({...carts}).then((res) => {
            console.log("res=",res);
            onRetGot(res);
            callback()
        })
            .catch((err) => {
                onRetGot(err);
                callback();
        })
    })
}

function update(carts, onRetGot, onErrGot) {
    let userid = carts.userid;
    let goodsid = carts.goodsid;
    let qty = carts.qty
    console.log(userid,goodsid,qty);

    executeQuery(collectionName, (collection, callback) => {
        collection.update({"userid":userid,"goodsid":goodsid},{$set:{"qty":qty}}).then((res) => {
            console.log("res=",res);
            onRetGot(res);
            callback()
        })
            .catch((err) => {
                onRetGot(err);
                callback();
        })
    })
}
//删除购物车商品
function remove(carts, onRetGot, onErrGot) {
    let userid = carts.userid;
    let goodsid = carts.goodsid;
    executeQuery(collectionName, (collection, callback) => {
        collection.deleteMany({ userid: userid, goodsid: { $in: goodsid } }).then((res) => {
            console.log("res=",res);
            onRetGot(res);
            callback()
        })
            .catch((err) => {
                onRetGot(err);
                callback();
        })
    })
}


function select(carts,onRetGot, onErrGot) {
    
    executeQuery(collectionName, (collection, callback) => {
        collection.find({}).count().then(async(res) => {
            let obj = {};
            obj.total = res;

            await collection.find({}).toArray().then((bbq => {
                obj.data = bbq;
            }))
            onRetGot(obj);
            callback()
        })
            .catch((err) => {
                onRetGot(err);
                callback();
        })
    })
}

module.exports = {
    add,
    update,
    remove,
    select,
}